using UnityEngine;
using UnityEditor;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Collections.Generic;

public class ParseMeshCollider : ParseObjectHandle<MeshCollider>
{
    public override void Prase(ExportSetting ExportSetting, MeshCollider obj, JArray jArray)
    {
        if (obj.sharedMesh == null)
        {
            return;
        }
        var ccMeshCollider = ExportSetting.CocosObjectConfig["cc.MeshCollider"].DeepClone();
        ccMeshCollider["_convex"] = obj.convex;
        ccMeshCollider["_isTrigger"] = obj.isTrigger;
        var meshJObject = new JObject();
        meshJObject["__expectedType__"] = "cc.Mesh";
        var mesh = obj.sharedMesh;
        var meshpath = AssetDatabase.GetAssetPath(mesh);
        var meshexstension = Path.GetExtension(meshpath);
        if (!Path.HasExtension(meshpath))
        {
            string defaultMeshUUID = (string)ExportSetting.CocosNodeConfig["DefalutMeshUUID"][AssetHelper.GetNameWithoutId(mesh)];

            string meshName = AssetHelper.GetIdName(mesh);
            if (defaultMeshUUID != null)
            {
                meshJObject["__uuid__"] = $"{defaultMeshUUID}";
            }
            else
            {
                meshJObject["__uuid__"] = $"{AssetHelper.GetObjectUUID(mesh)}@{AssetHelper.GetMetaIdByName($"{meshName}.mesh")}";
                AssetHelper.CreateGltfAndMeta(ExportSetting, mesh);
            }
        }
        else
        {
            mesh.name = AssetHelper.GetIdName(mesh);
            var asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(meshpath);
            var assets = AssetDatabase.LoadAllAssetsAtPath(meshpath);
            if (assets.Length > 1)
            {
                var meshes = new List<Mesh>();
                foreach (var item in assets)
                {
                    if (item is Mesh tempMesh)
                    {
                        meshes.Add(tempMesh);
                    }
                }
                if (meshes.IndexOf(mesh) == 0)
                {
                    mesh.name = AssetHelper.GetIdName(asset);
                }

            }
            string meshuuid = AssetHelper.GetObjectUUID(asset);
            meshJObject["__uuid__"] = $"{meshuuid}@{AssetHelper.GetMetaIdByName($"{mesh.name}.mesh")}";
            mesh.name = AssetHelper.GetIdName(mesh);
            if (meshexstension == ".asset")
            {
                AssetHelper.CreateGltfAndMeta(ExportSetting, mesh);
            }
            else
            {
                AssetHelper.CreateGltfAndMeta(ExportSetting, asset as GameObject);
            }
        }
        ccMeshCollider["_mesh"] = meshJObject;
        jArray.Add(ccMeshCollider);
    }
}
